﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Drawing;
using System.Text.RegularExpressions;
using System.Web;
using BusinessLogic.ClassFactory;
using Common;
using LitJson;
using ValidateCommon;
using DataAccess;

namespace Util.BasePage
{
    public class BasePage : System.Web.UI.Page
    {
        public BasePage()
            : base()
        {
        }

        public virtual void Alert(string strMsg)
        {
            this.ClientScript.RegisterStartupScript(Page.ClientScript.GetType(), "msg", "<script>alerttispage(\"" + strMsg.Replace("\r\n", "") + "\",'2秒后自动关闭','var unuserdparams=1')</script>");
        }

        /// <summary>
        /// 提示并重定向到指定页
        /// </summary>
        /// <param name="strMsg"></param>
        /// <param name="strUrl">重定向的URL</param>
        /// <param name="blnNewWindow">是否新打开窗口</param>
        public void AlertAndRedirect(string strMsg, string strUrl, bool blnNewWindow)
        {
            string strScript = string.Empty;
            if (blnNewWindow == false)
            {
                strScript = string.Format("<script language=\"javascript\">alerttispage(\"{0}\",'自动跳转，请稍候','window.location.href=\"{1}\"'); </script>", strMsg.Replace("\r\n", ""), strUrl);
            }
            else
            {
                strScript = string.Format("<script language=\"javascript\">alerttispage(\"{0}\",'自动跳转，请稍候', 'window.open(\"{1}\"');</script>", strMsg.Replace("\r\n", ""), strUrl);
            }
            RegisterStartupScript("msg", strScript);
        }

        /// <summary>
        /// 执行命令，提示并重定向到指定页
        /// </summary>
        /// <param name="strMsg"></param>
        /// <param name="strUrl">重定向的URL</param>
        /// <param name="blnNewWindow">是否新打开窗口</param>
        /// <param name="stringCommand">要执行的命令</param>
        public void AlertAndRedirectAndExecOther(string strMsg, string strUrl, bool blnNewWindow, string stringCommand)
        {
            string strScript = string.Empty;
            if (blnNewWindow == false)
            {
                strScript = string.Format("<script language=\"javascript\">{0};alerttispage(\"{1}\"); window.location.href=\"{2}\";</script>", stringCommand, strMsg.Replace("\r\n", ""), strUrl);
            }
            else
            {
                strScript = string.Format("<script language=\"javascript\">{0};alerttispage(\"{1}\"); window.open(\"{2}\");</script>", stringCommand, strMsg.Replace("\r\n", ""), strUrl);
            }
            RegisterStartupScript("msg", strScript);
        }

        /// <summary>
        /// 进行其他自定义操作并弹出提示
        /// </summary>
        /// <param name="strMsg"></param>
        /// <param name="stringCommand">自定义命令</param>
        public void AlertAndExecOther(string strMsg, string strinfo, string stringCommand)
        {
            string strScript = string.Empty;
            strScript = string.Format("<script language=\"javascript\">alerttispage(\"{0}\",\"{1}\",\"{2}\"); </script>", strMsg.Replace("\r\n", ""), strinfo.Replace("\r\n", ""), stringCommand);
            RegisterStartupScript("custommsg", strScript);
        }

        /// <summary>
        /// 提示并重定向到指定页
        /// </summary>
        /// <param name="strMsg"></param>
        /// <param name="strUrl">重定向的URL</param>
        /// <param name="blnNewWindow">是否新打开窗口</param>
        public void IsAndRedirect(string strUrl, bool blnNewWindow)
        {
            string strScript = string.Empty;
            if (blnNewWindow == false)
            {
                strScript = string.Format("<script language=\"javascript\">window.location.href=\"{0}\";</script>", strUrl);
            }
            else
            {
                strScript = string.Format("<script language=\"javascript\">window.open(\"{0}\");</script>", strUrl);
            }
            RegisterStartupScript("msg", strScript);
        }

        public static string ClearHTMLAndSQL(string Htmlstring)  //替换HTML标记
        {
            //删除脚本
            Htmlstring = Regex.Replace(Htmlstring, @"<script[^>]*?>.*?</script>", "", RegexOptions.IgnoreCase);
            //删除HTML
            Htmlstring = Regex.Replace(Htmlstring, @"<(.[^>]*)>", "", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"([\r\n])[\s]+", "", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"-->", "", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"<!--.*", "", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&(quot|#34);", "\"", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&(amp|#38);", "&", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&(lt|#60);", "<", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&(gt|#62);", ">", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&(nbsp|#160);", " ", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&(iexcl|#161);", "\xa1", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&(cent|#162);", "\xa2", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&(pound|#163);", "\xa3", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&(copy|#169);", "\xa9", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&#(\d+);", "", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"<img[^>]*>;", "", RegexOptions.IgnoreCase);
            Htmlstring.Replace("<", "");
            Htmlstring.Replace(">", "");
            Htmlstring.Replace("\r\n", "");
            Htmlstring = HttpContext.Current.Server.HtmlEncode(Htmlstring).Trim();
            return Htmlstring;
        }

        /// <summary>
        /// 生成缩略图
        /// </summary>
        /// <param name="M_OriginalImagePath">源图路径（物理路径）</param>
        /// <param name="M_ThumbnailPath">缩略图路径（物理路径）</param>
        /// <param name="M_Width">缩略图宽度</param>
        /// <param name="M_Height">缩略图高度</param>
        public void CreateThumb(string M_OriginalImagePath, string M_ThumbnailPath, int M_Width, int M_Height)
        {
            System.Drawing.Image originalImage = System.Drawing.Image.FromFile(M_OriginalImagePath);
            int towidth = 0;
            int toheight = 0;
            if (originalImage.Width >= originalImage.Height)
            {
                if (originalImage.Width >= M_Width)
                {
                    towidth = M_Width;
                    decimal decYinZi = (decimal)M_Width / originalImage.Width;
                    toheight = Convert.ToInt32(decYinZi * originalImage.Height);
                }
                else
                {
                    towidth = originalImage.Width;
                    toheight = originalImage.Height;
                }
            }
            else
            {
                if (originalImage.Height >= M_Height)
                {
                    toheight = M_Height;
                    decimal decYinZi = (decimal)M_Height / originalImage.Height;
                    towidth = Convert.ToInt32(decYinZi * originalImage.Width);
                }
                else
                {
                    towidth = originalImage.Width;
                    toheight = originalImage.Height;
                }
            }

            int x = 0;//左上角的x坐标
            int y = 0;//左上角的y坐标
            //新建一个bmp图片
            System.Drawing.Image bitmap = new System.Drawing.Bitmap(towidth, toheight);
            //新建一个画板
            Graphics g = System.Drawing.Graphics.FromImage(bitmap);
            //设置高质量插值法
            g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
            //设置高质量,低速度呈现平滑程度
            g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
            //清空画布并以透明背景色填充
            g.Clear(Color.Transparent);
            //在指定位置并且按指定大小绘制原图片的指定部分
            g.DrawImage(originalImage, x, y, towidth, toheight);
            try
            {
                //以jpg格式保存缩略图
                bitmap.Save(M_ThumbnailPath, System.Drawing.Imaging.ImageFormat.Jpeg);
            }
            catch (System.Exception e)
            {
                throw e;
            }
            finally
            {
                originalImage.Dispose();
                bitmap.Dispose();
                g.Dispose();
            }
        }

        /// <summary>
        /// 构建栏目树
        /// </summary>
        public string BuildSectionTree()
        {
            using (DBManager objDBManager = new DBManager())
            {
                try
                {
                    List<Hashtable> hashSectionTree = new List<Hashtable>();
                    using (SectionsFactory objSectionsFactory = new SectionsFactory(objDBManager))
                    {
                        BusinessLogic.BusinessRules.Sections objSections =
                            objSectionsFactory.CreatorBySql("intParentID =0 and intWSID=" + RichECMS.State.intWSID +
                                                             " order by intSortNo desc,  dtmInTime desc ");

                        for (int i = 0; i < objSections.Count; i++)
                        {
                            hashSectionTree.Add(FildChildFileAndDorectory(objSections));
                            objSections.SelectRow(i + 1);
                        }
                    }
                    return JsonMapper.ToJson(hashSectionTree);
                }
                catch (Exception)
                {

                    throw;
                }

            }
        }

        //递归查找
        private Hashtable FildChildFileAndDorectory(BusinessLogic.BusinessRules.Sections objsection)
        {
            try
            {
                Hashtable hashresult = new Hashtable();
                hashresult["name"] = objsection.DataItem.chvSTCName;
                hashresult["sid"] = objsection.DataItem.intSectionID;
                hashresult["open"] = false;
                hashresult["lifetype"] = "life";
                hashresult["isParent"] = false;
                //hashresult["iconSkin"] = "life";
                using (SectionsFactory objFactory = new SectionsFactory())
                {
                    BusinessLogic.BusinessRules.Sections objsectionTemp =
                        objFactory.CreatorBySql("intParentID =" +
                                                objsection.DataItem.intSectionID.ToString() +
                                                " and intWSID=" + RichECMS.State.intWSID +
                                                " order by intSortNo desc,dtmInTime desc");
                    if (objsectionTemp != null)
                    {
                        hashresult["lifetype"] = "parent";
                        //hashresult["iconSkin"] = "parent";
                        hashresult["isParent"] = true;
                        List<Hashtable> hashlisttemp = new List<Hashtable>();
                        for (int i = 0; i < objsectionTemp.Count; i++)
                        {
                            hashlisttemp.Add(FildChildFileAndDorectory(objsectionTemp));
                            objsectionTemp.SelectRow(i + 1);
                        }
                        hashresult["children"] = hashlisttemp;
                    }
                }
                return hashresult;
            }
            catch (Exception)
            {
                throw;
            }
        }
    }
}